package com.graduation.smartparkingplatform.Scheduler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.graduation.smartparkingplatform.Dao.DistinguishMapper;
import com.graduation.smartparkingplatform.Dao.PayingRecordMapper;
import com.graduation.smartparkingplatform.Dao.RecordMapper;
import com.graduation.smartparkingplatform.Dao.UserMapper;
import com.graduation.smartparkingplatform.Pojo.Distinguish;
import com.graduation.smartparkingplatform.Pojo.PayingRecord;
import com.graduation.smartparkingplatform.Pojo.Space;
import com.graduation.smartparkingplatform.WebSocket.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@Slf4j
@Configuration // 1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling // 2.开启定时任务
@Async // 异步执行
public class Scheduler {

  @Autowired RedisTemplate redisTemplate;
  @Autowired private PayingRecordMapper payingRecordMapper;
  @Autowired private UserMapper userMapper;
  @Autowired private DistinguishMapper distinguishMapper;
  @Autowired private RecordMapper recordMapper;

  // 停车场实时数据
  @Scheduled(fixedRate = 5000)
  private void sendSpace() throws IOException {
    //    Jedis jedis = null;
    try {
      //      jedis = RedisUtil.getJedis();
      JSONObject result = new JSONObject();
      List<Space> spaceList = new ArrayList<>();
      String patternKey = "spaceNo_*";
      Set<String> keys = redisTemplate.keys(patternKey);
      //      Set<String> keys = RedisUtil.keys(patternKey);
      for (String str : keys) {
        //        String jsonStr = RedisUtil.stringGet(str);
        String jsonStr = (String) redisTemplate.opsForValue().get(str);
        Space space = JSON.parseObject(jsonStr, Space.class);
        spaceList.add(space);
      }
      result.put("webSocketId", 1);
      result.put("spaceList", spaceList);
      WebSocket.sendInfo(JSONObject.toJSONString(result, SerializerFeature.WriteMapNullValue));
    } catch (Exception e) {
      log.error("Scheduled sendSpace error-" + e);
      e.printStackTrace();
    }
    //    finally {
    //      System.out.println(jedis);
    //      RedisUtil.close(jedis);
    //    }
  }

  // 今天收费记录
  @Scheduled(fixedRate = 5000)
  private void PayingRecord_Today() {
    try {
      JSONObject result = new JSONObject();
      double total_today = 0;
      double total_week = 0;
      double total_month = 0;
      List<PayingRecord> payingRecord_today = payingRecordMapper.PayingRecord_Today();
      List<PayingRecord> payingRecord_week = payingRecordMapper.PayingRecord_Week();
      List<PayingRecord> payingRecord_month = payingRecordMapper.PayingRecord_Month();
      for (PayingRecord record : payingRecord_today) {
        BigDecimal payCount = record.getPay_amount();
        total_today += payCount.doubleValue();
      }
      for (PayingRecord record : payingRecord_week) {
        BigDecimal payCount = record.getPay_amount();
        total_week += payCount.doubleValue();
      }
      for (PayingRecord record : payingRecord_month) {
        BigDecimal payCount = record.getPay_amount();
        total_month += payCount.doubleValue();
      }
      result.put("webSocketId", 2);
      result.put("Total_today", total_today);
      result.put("total_week", total_week);
      result.put("total_month", total_month);
      WebSocket.sendInfo(result.toJSONString());
    } catch (Exception e) {
      log.error("Scheduled PayingRecord_Today error-" + e);
      e.printStackTrace();
    } // websocket推送数据
  }

  // 用户数量 + 访客数量
  @Scheduled(fixedRate = 5000)
  private void User_count() {
    try {
      JSONObject result = new JSONObject();
      Integer Count_user = userMapper.Count_user();
      Integer Count_visitor = userMapper.Count_visitor();
      result.put("webSocketId", 3);
      result.put("Count_user", Count_user);
      result.put("Count_visitor", Count_visitor);
      WebSocket.sendInfo(result.toJSONString());
    } catch (Exception e) {
      log.error("Scheduled User_count error-" + e);
      e.printStackTrace();
    } // websocket推送数据
  }

  // 今日进出场数量 + 全国省份进入停车场数据
  @Scheduled(fixedRate = 10000)
  private void Distinguish_count() {
    try {
      JSONObject result = new JSONObject();
      Map<String, Integer> province = new HashMap<String, Integer>();
      List<Distinguish> Distinguish_list_In = distinguishMapper.Distinguish_list_In("进");
      List<Distinguish> Distinguish_list_In_all = distinguishMapper.Distinguish_list_In_all("进");
      Integer Distinguish_count_In = Distinguish_list_In.size();
      Integer Distinguish_count_Out = distinguishMapper.Distinguish_count_Out("出");
      for (Distinguish distinguish : Distinguish_list_In_all) {
        String carPlate_province = distinguish.getCar_plate().substring(0, 1); //  取出省份简称
        if (province.containsKey(carPlate_province)) {
          Integer total = province.get(carPlate_province);
          province.put(carPlate_province, total + 1);
        } else {
          province.put(carPlate_province, 1);
        }
      }
      result.put("webSocketId", 4);
      result.put("Distinguish_count_In", Distinguish_count_In);
      result.put("Distinguish_count_Out", Distinguish_count_Out);
      result.put("carPlate_province", province);
      WebSocket.sendInfo(result.toJSONString());
    } catch (Exception e) {
      log.error("Scheduled Distinguish_count error-" + e);
      e.printStackTrace();
    } // websocket推送数据
  }

  // 现停车数+总停车数
  @Scheduled(fixedRate = 5000)
  private void Parking_count() {
    //    Jedis jedis = null;
    try {
      //      jedis = RedisUtil.getJedis();
      JSONObject result = new JSONObject();
      Integer Parking_count = recordMapper.Parking_count();
      String patternKey = "spaceNo_*";
      //      Set<String> keys = RedisUtil.keys(patternKey);
      Set<String> keys = redisTemplate.keys(patternKey);
      int total = 0;
      for (String str : keys) {
        //        String jsonStr = RedisUtil.stringGet(str);
        String jsonStr = (String) redisTemplate.opsForValue().get(str);
        Space space = JSON.parseObject(jsonStr, Space.class);
        if (space.getSpace_status()) {
          total++;
        }
      }
      result.put("webSocketId", 5);
      result.put("parking_count", Parking_count);
      result.put("parking_now", total);
      WebSocket.sendInfo(result.toJSONString());
    } catch (Exception e) {
      log.error("Scheduled Parking_count error-" + e);
      e.printStackTrace();
    }
    //    finally {
    //      RedisUtil.close(jedis);
    //    }
  }

  // 栏杆状态
  @Scheduled(fixedRate = 1000)
  private void Railing_status() {
    try {
      Map<String, Object> map = new HashMap<>();
      String Railing_in = (String) redisTemplate.opsForValue().get("Railing_in");
      String Railing_out = (String) redisTemplate.opsForValue().get("Railing_out");
      if (Railing_in.equals("sys_close") || Railing_in.equals("car_close")) {
        map.put("Railing_in", false);
      } else {
        map.put("Railing_in", true);
      }
      if (Railing_out.equals("sys_close") || Railing_out.equals("car_close")) {
        map.put("Railing_out", false);
      } else {
        map.put("Railing_out", true);
      }
      JSONObject result = new JSONObject(map);
      result.put("webSocketId", 6);
      WebSocket.sendInfo(result.toJSONString());
    } catch (Exception e) {
      log.error("Scheduled Railing_status error-" + e);
      e.printStackTrace();
    } // websocket推送数据
  }
}
